package me.ingxin.android.drawable

import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.drawable.Drawable
import android.text.style.DynamicDrawableSpan
import java.lang.ref.WeakReference

/**
 * Created by ingxin on 2022/6/14
 * 居中对齐的ImageSpan
 */
class CenterImageSpan(
    private val drawable: Drawable,
    private val marginStart: Int = 0,
    private val marginEnd: Int = 0
) : DynamicDrawableSpan() {

    private var drawableRef: WeakReference<Drawable>? = null

    override fun getDrawable(): Drawable {
        return drawable
    }

    override fun draw(
        canvas: Canvas,
        text: CharSequence?,
        start: Int,
        end: Int,
        x: Float,
        top: Int,
        y: Int,
        bottom: Int,
        paint: Paint
    ) {
        val d = getCachedDrawable()
        val fm = paint.fontMetricsInt
        val transY = (y + fm.descent + y + fm.ascent) / 2 - (d.bounds.bottom + d.bounds.top) / 2
        canvas.save()
        canvas.translate(marginStart + x, transY.toFloat())
        d.draw(canvas)
        canvas.restore()
    }

    override fun getSize(
        paint: Paint,
        text: CharSequence?,
        start: Int,
        end: Int,
        fm: Paint.FontMetricsInt?
    ): Int {
        return marginStart + marginEnd + super.getSize(paint, text, start, end, fm)
    }

    private fun getCachedDrawable(): Drawable {
        return drawableRef?.get() ?: getDrawable().also { drawableRef = WeakReference(it) }
    }

}